package com.cskaoyan._04tx;

import com.cskaoyan._03jdbc.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author Macro_Ray
 * @since 2024/4/18 下午10:17
 */
public class TransferMoney {
    public static void main(String[] args) throws SQLException {
        // 使用Scanner来模拟进行转账的双方信息：转发方姓名、转入放姓名、金额
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入转账方姓名：");
        String transferor = scanner.nextLine();
        System.out.println("请输入转入方姓名：");
        String transferee = scanner.nextLine();
        System.out.println("请输入金额");
        double amount = scanner.nextDouble();

        Connection connection = null; // 数据库连接
        PreparedStatement preparedStatement = null; // 预编译语句
        try{
            connection = JdbcUtils.getConnection(); // 获取数据库连接
            // 需要开启事务，保障原子性
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement("update account set balance = balance -? where name =?");
            preparedStatement.setDouble(1, amount);
            preparedStatement.setString(2, transferor);
            preparedStatement.executeUpdate();

            int i =1/0; // 模拟转账失败
            // 转入方
            preparedStatement.setDouble(1, -amount);
            preparedStatement.setString(2, transferee);
            preparedStatement.executeUpdate();
            connection.commit(); // 提交事务
        } catch (SQLException e) {
            try{
                connection.rollback(); // 回滚事务
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }finally{
            JdbcUtils.close(connection, preparedStatement, null); // 关闭数据库连接、预编译语句、结果集
        }
    }
}
